package com.hxd.mall.module.product.home

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import com.hexin.locallibrary.banner.BannerConfig
import com.hxd.mall.R
import com.hxd.mall.R.drawable.shape_gray_bg_rectangle
import com.hxd.mall.R.drawable.shape_white_bg_rectangle
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_title_name
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.key_web_url
import com.hxd.mall.constant.HxdConstantsRouterPath.Product.path_hxd_home_detail
import com.hxd.mall.module.MainActivity
import com.hxd.mall.module.product.home.bean.ColorBean
import com.hxd.mall.module.product.home.bean.HomeTypeBean
import com.hxd.mall.module.product.home.bean.Resource
import com.hxd.mall.utils.local.NavigationUtil.jumpToWebView
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.local.getNewListAdapter
import com.hxd.mall.utils.local.initBannerView
import com.hxd.mall.utils.open.UIUtil
import com.hxd.mall.utils.open.initGridRecyclerView
import kotlinx.android.synthetic.main.home_top_fg_layout.view.*
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.dip
import org.jetbrains.anko.displayMetrics
import org.jetbrains.anko.forEachChildWithIndex

/**
 * Create by yinzhengwei on 2019-11-11
 * @Function
 */
class HomeTopView(context: Context, singleLine: Boolean) : LinearLayout(context, null, 0) {

    private var current = 0

    fun changeColor() {
        //切换顶部背景色
        if ((context as MainActivity).current == 0) {
            try {
                //修改顶部区域的背景色
                val ext = mHomeBean?.data?.bannerLayout?.resources!![current].ext
                if (ext != null) {
                    view_top_bg.setBackgroundColor(Color.parseColor(ext.rgb))

                    val drawable = ContextCompat.getDrawable(context, shape_white_bg_rectangle) ?: return
                    val bean = ColorBean(Color.parseColor(ext.rgb), Color.WHITE, drawable, ContextCompat.getDrawable(context, R.drawable.home_type_bottom_line)!!)
                    EventBus.getDefault().post(bean)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            ColorBean(
                Color.WHITE,
                Color.parseColor("#FFDB3533"),
                ContextCompat.getDrawable(context, shape_gray_bg_rectangle)!!,
                ContextCompat.getDrawable(context, R.drawable.home_type_bottom_red_line)!!
            ).run {
                EventBus.getDefault().post(this)
            }
        }
    }

    //金刚活动区
    private val activeListAdapter = ActiveListAdapter()
    //品牌区
    private val mLimitadapter = LimitListAdapter()
    private var mHomeBean: HomeTypeBean? = null

    private fun setViewHeight(view: View, height: Int) {
        val layoutParams = view.layoutParams
        layoutParams.height = height
        view.layoutParams = layoutParams
    }

    init {
        LayoutInflater.from(context).inflate(R.layout.home_top_fg_layout, this)
        val height = (context.displayMetrics.widthPixels - context.dip(24)) * 2 / 5
        setViewHeight(banner, height)
        setViewHeight(banner_Img, height / 2)
        setViewHeight(view_top_bg, view_top_bg.layoutParams.height - context.dip(12))

        //猜你喜欢文案首页和全部tab显示
        if (singleLine) {
            tv_tip.visibility = View.GONE
        }
    }

    private var isPlay = true
    fun banner(isPlay: Boolean) {
        this.isPlay = isPlay
        if (isPlay) banner.startAutoPlay() else banner.stopAutoPlay()
    }

    fun reLoad(mHomeBean: HomeTypeBean?) {
        this.mHomeBean = mHomeBean

        //顶部banner
        isListEmpty(mHomeBean?.data?.bannerLayout?.resources, layout_banner) { list ->
            initBannerView(banner, list, bannerStyle = BannerConfig.NOT_INDICATOR, corner = 0) {

                current = it

                changePointIndex(it)

                //只有首页切换顶部背景色
                if ((context as MainActivity).current == 0)
                    changeColor()
            }
            //添加banner的下标点
            addPoint(list)

            changePointIndex(0)
        }

        //广告图
        isListEmpty(mHomeBean?.data?.bulletinLayout?.resources, banner_Img) {
            initBannerView(banner_Img, it) {}
        }

        initActiveListView()
        initLimitListView()
    }

    //品牌图片活动区域
    private fun initLimitListView() {
        isListEmpty(mHomeBean?.data?.campaignLayout?.resources, opera_ist) { item ->
            if (opera_ist!!.childCount > 0) {
                getNewListAdapter(item, mLimitadapter, "niche_click")
            } else {
                opera_ist?.initGridRecyclerView(getNewListAdapter(item, mLimitadapter, "niche_click"), rowSpace = 3, columnSpace = 3, spanCount = 2)
            }
        }
    }

    //金刚活动区域
    private fun initActiveListView() {
        isListEmpty(mHomeBean?.data?.channelLayout?.resources, activeList) {
            if (activeList!!.childCount > 0)
                getNewListAdapter(it, activeListAdapter, "niche_click")
            else
                activeList!!.initGridRecyclerView(getNewListAdapter(it, activeListAdapter, point = "icon_number_click"), rowSpace = 10, spanCount = 5)

            activeListAdapter.setOnItemClickListener { _, _, position ->

                mHomeBean?.data?.channelLayout?.resources?.run {
                    val resource = this[position]
                    if (resource.entryType == "H5")
                        jumpToWebView(resource.title ?: "", resource.entryUri ?: "")
                    else
                        routerNavigation(path_hxd_home_detail, mutableMapOf(key_web_url to resource.entryUri.toString(), key_title_name to resource.title.toString()))
                }
            }
        }
    }

    private fun isListEmpty(resources: List<Resource>?, viewGroup: ViewGroup, callback: (List<Resource>) -> Unit) {
        if (resources != null) {
            viewGroup.visibility = View.VISIBLE
            callback(resources)
        } else {
            viewGroup.visibility = View.GONE
        }
    }

    //添加banner的下标点view
    private fun addPoint(list: List<Resource>) {
        layout_page_point.removeAllViews()
        if (list.size <= 1)
            return
        list.forEach { _ ->
            layout_page_point.addView(View(context).apply {
                if (list.size == 1) {
                    setBackgroundResource(R.drawable.banner_select)
                } else {
                    setBackgroundResource(R.drawable.banner_unselect)
                }
                this.layoutParams = LayoutParams(UIUtil.dip2px(5), UIUtil.dip2px(5)).apply {
                    leftMargin = UIUtil.dip2px(3)
                    rightMargin = UIUtil.dip2px(3)
                }
            })
        }
    }

    private fun changePointIndex(index: Int) {
        layout_page_point.forEachChildWithIndex { i, view ->
            if (i == index)
                view.setBackgroundResource(R.drawable.banner_select)
            else
                view.setBackgroundResource(R.drawable.banner_unselect)
        }
    }

}